package com.test.thread;

/**
 * Created with IntelliJ IDEA.
 * User: lxf
 * Date: 2016/8/30
 * Time: 14:14
 * To change this template use Editor | File and Code Templates.
 */
public class Sale extends Thread {

    private Object lock;

    public Sale(Object l) {
        lock = l;
    }

    @Override
    public void run() {

        while (true) {
            try {
                synchronized (lock) {
                    if (Product.bread <= 0) {
                        System.out.println("等待购买，当前没有面包可以购买");
                        lock.wait();
                    } else {
                        Product.bread--;
                        System.out.println("买走了一个面包，剩余面包数量：" + Product.bread);
                        Thread.sleep(2000);
                        if (Product.bread < 3) {
                            lock.notifyAll();
                            lock.wait();
                        }
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}
